package com.yan.utils;

import com.alibaba.fastjson.JSON;

import java.io.UnsupportedEncodingException;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.AbstractJsonMessageConverter;
import org.springframework.amqp.support.converter.AbstractMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;

/**
 * @Description: 生产者生产的数据转换为json存入消息队列
 * @Version: 1.0
 * @Author:周磊
 * @Email: zhoulei@new4g.cn
 * @Date:2015年11月9日14:35:03
 */
public class FastJsonMessageConverter extends AbstractMessageConverter {
    public static final String DEFAULT_CHARSET = "UTF-8";
    private volatile String defaultCharset = "UTF-8";

    public void setDefaultCharset(String defaultCharset) {
        this.defaultCharset = (defaultCharset != null ? defaultCharset : "UTF-8");
    }

    public Object fromMessage(Message message)
            throws MessageConversionException {
        return null;
    }

    protected Message createMessage(Object objectToConvert, MessageProperties messageProperties)
            throws MessageConversionException {
        byte[] bytes = null;
        try {
            String jsonString = JSON.toJSONString(objectToConvert);

            bytes = jsonString.getBytes(this.defaultCharset);
        } catch (UnsupportedEncodingException e) {
            throw new MessageConversionException("Failed to convert Message content", e);
        }

        messageProperties.setContentType("application/json");

        messageProperties.setContentEncoding(this.defaultCharset);

        if (bytes != null) {
            messageProperties.setContentLength(bytes.length);
        }
        return new Message(bytes, messageProperties);
    }
}